import prisma from './prisma.service';
import { MessageType, Prisma } from '@prisma/client';

class MessageService {
    createUserMessage(data: {
        senderId: string;
        receiverId: string;
        content: string;
        type?: MessageType;
        fileSize?: number;
        fileName?: string;
    }) {
        return prisma.message.create({ data });
    }

    createGroupMessage(data: {
        senderId: string;
        groupId: string;
        content: string;
        type?: MessageType;
        fileSize?: number;
        fileName?: string;
    }) {
        return prisma.message.create({ data });
    }

    async getMessage(id: number) {
        return prisma.message.findUnique({ where: { id } });
    }

    async getOfflineMessages(userId: string, after: Date, limit = 100) {
        let where: Prisma.MessageWhereInput = {
            OR: [
                {
                    receiverId: userId,
                    groupId: null,
                },
                {
                    receiverId: null,
                    group: {
                        members: {
                            some: { userId }
                        }
                    }
                }
            ],

        }
        if (after) {
            where.createdAt = {
                gt: after,
            }
        }
        return prisma.message.findMany({
            where,
            orderBy: { createdAt: 'desc' },
            take: limit
        });
    }
}

const messageService = new MessageService();
export default messageService;